package com.yqr.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @program: springclouddubbotest
 * @description: 抽象通用service实现
 * @author: Mr.Qian
 * @create: 2021-04-15 22:56
 **/
public class BaseServiceImpl<T> implements BaseService<T> {
    
    @Autowired
    private Mapper<T> mapper;
    
    @Override
    public T selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }
    
    @Override
    public List<T> selectAll() {
        return mapper.select(null);
    }
    
    @Override
    public T selectOne(T record) {
        return mapper.selectOne(record);
    }
    
    @Override
    public List<T> selectListByWhere(T record) {
        return mapper.select(record);
    }
    
    @Override
    public PageInfo<T> selectPageListByWhere(T record, Integer page, Integer rows) {
        PageHelper.startPage(page, rows);
        List<T> list = mapper.select(record);
        return new PageInfo<T>(list);
    }
    
    @Override
    public Integer add(T record) {
//        try {
//            Method setCreated = record.getClass().getMethod("setCreated", Date.class);
//            setCreated.invoke(record, new Date());
//
//            Method getCreated = record.getClass().getMethod("getCreated");
//            Date date = (Date) getCreated.invoke(record);
//
//            Method setUpdated = record.getClass().getMethod("setUpdated", Date.class);
//            setUpdated.invoke(record, date);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return mapper.insert(record);
    }
    
    @Override
    public Integer updateSelective(T record) {
//        try {
//            Method setUpdated = record.getClass().getMethod("setUpdated", Date.class);
//            setUpdated.invoke(record, new Date());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return mapper.updateByPrimaryKeySelective(record);
    }
    
    @Override
    public Integer deleteById(Integer id) {
        return mapper.deleteByPrimaryKey(id);
    }
    
    @Override
    public Integer deleteByPreportys(Class<T> clazz, String preporty, Object[] values) {
        Example example = new Example(clazz);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn(preporty, Arrays.asList(values));
        return mapper.deleteByExample(example);
    }
    
    @Override
    public Integer deleteByWhere(T record) {
        return mapper.delete(record);
    }
    
}
